package orm

import (
	"fmt"
	"reflect"
	"sync"
	"time"
)

type ScanPool struct {
	Pool map[int64]map[string]interface{}
}

var scanCachePool *ScanPool
var mt *sync.Mutex

func init() {
	scanCachePool = NewScanPool()
	mt = new(sync.Mutex)
}

func GetCache(id int, v interface{}) (interface{}, bool) {
	return scanCachePool.Get(id, v)
}

func SetCache(id int, v interface{}) {
	scanCachePool.Set(id, v)
}

func NewScanPool() *ScanPool {
	return &ScanPool{
		Pool: make(map[int64]map[string]interface{}),
	}
}

func (this *ScanPool) Get(id int, v interface{}) (interface{}, bool) {
	t := reflect.TypeOf(v)
	for timestamp, secondPool := range this.Pool {
		if timestamp < time.Now().Unix()-2 {
			//2秒以前的数据无效，并且抛弃，防止出现微妙跨两个区间的时候取不到值
			mt.Lock()
			delete(this.Pool, timestamp)
			mt.Unlock()
			continue
		}
		mt.Lock()
		find, ok := secondPool[fmt.Sprintf("%s_%d", t.String(), id)[1:]]
		mt.Unlock()
		return find, ok
	}
	return nil, false
}

func (this *ScanPool) Set(id int, v interface{}) {
	t := reflect.TypeOf(v)
	if this.Pool[time.Now().Unix()] == nil {
		this.Pool[time.Now().Unix()] = make(map[string]interface{})
	}
	mt.Lock()
	defer mt.Unlock()
	this.Pool[time.Now().Unix()][fmt.Sprintf("%s_%d", t.String(), id)[1:]] = v
}
